package com.demo.controller;

import cn.hutool.core.lang.Console;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.demo.dao.BugMapper;
import com.demo.entity.Bug;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Component
@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
@Slf4j
public class StaticScheduleTask {
    @Autowired
    private BugMapper bugMapper;

    //3.添加定时任务
    @Scheduled(cron = "0 0 23 * * ? ")
    private void configureTasks() throws InterruptedException {
        List<Bug> list = bugMapper.select();
        for (Bug bug : list) {
            post(bug.getName(),bug.getNum());
        }
        log.info("执行静态定时任务时间: " + LocalDateTime.now());
    }


    /**
     * vika 新增数据 bug统计
     */
    public void post(String type,String num) {
        String jsonStr = "{\n" +
                "  \"records\": [\n" +
                "  {\n" +
                "    \"fields\": {\n" +
                "      \"日期\": {},\n" +
                "      \"产品\": [\n" +
                "        \"{}\"\n" +
                "      ],\n" +
                "      \"bug数\": {}\n" +
                "    }\n" +
                "  }\n" +
                "],\n" +
                "  \"fieldKey\": \"name\"\n" +
                "}";
        jsonStr = StrUtil.format(jsonStr, new Date().getTime(), type, num);
        //方法一：使用工具类转换
        //JSONObject jsonObject = JSONUtil.parseObj(jsonStr);
        String result = HttpRequest.post("https://api.vika.cn/fusion/v1/datasheets/dst8RzW8LJEED24HcR/records?viewId=viwvqoTAS7cPy&fieldKey=name")
                .header("Authorization", "Bearer usk5qG8r5fAu0LF6AEckolI")
                .header("Content-Type", "application/json")
                .body(jsonStr)
                .timeout(20000)
                .execute().body();
        Console.log(result);
    }
}
